<template>
  <div class="h-full">
    <img src="@/assets/background.jpg" alt="" />
    <img class="w-20 h-20 mx-auto -mt-10" src="../assets/logo.png" />
    <van-form class="mt-8 mx-6" validate-first @submit="onSubmit" ref="form">
      <van-field
        class="py-4"
        v-model="mobile"
        name="mobile"
        ref="mobile"
        label="手机号"
        placeholder="请输入手机号"
        :rules="[{ pattern, message: '手机号格式错误', trigger: 'onBlur' }]"
      />
      <van-field
        class="py-4"
        v-model="code"
        name="code"
        :rules="[{ required: true, message: '请输入短信验证码' }]"
        center
        clearable
        label="验证码"
        placeholder="请输入短信验证码"
      >
        <template #button>
          <van-button
            :loading="$loading"
            :disabled="smsDisable"
            native-type="button"
            @click.stop="sendSms"
            size="small"
            type="primary"
            class="w-16"
            >{{ smsSendBtnText }}</van-button
          >
        </template>
      </van-field>

      <div class="mt-8 mx-4">
        <van-button block type="primary" native-type="submit">登 录</van-button>
      </div>
      <!-- <p class="mt-4 text-center text-sm">
        没有账号？
        <span class="text-blue-400" @click="$router.push('/register')">
          账号注册
        </span>
      </p> -->
    </van-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      mobile: '',
      code: '',
      pattern: /^[1][3,4,5,7,8,9][0-9]{9}$/,
      smsDisable: false,
      smsSendBtnText: '发送',
      seconds: 60,
    }
  },
  methods: {
    sendSms() {
      this.$refs.mobile.validate().then(err => {
        if (err) {
          return
        }
        this.smsDisable = true
        let tik = setInterval(() => {
          this.smsSendBtnText = `${this.seconds} 秒`
          this.seconds--
          if (this.seconds === 0) {
            clearInterval(tik)
            this.smsDisable = false
            this.seconds = 60
            this.smsSendBtnText = '发送'
          }
        }, 1000)

        this.axios.post('/sms/code_login', { mobile: this.mobile }).then(res => {
          if (res.data.code === 1) {
            this.$toast.success('发送成功')
          }else{
            this.$toast.fail(res.data.msg)
          }
        })
      })
    },
    onSubmit(values) {
      this.axios.post('/member/login', values).then(res => {
        if (res.data.msg == 'ok') {
          this.$toast.success('登录成功')
          this.$store.commit('setLoginInfo', res.data.data)
          const user = this.$store.state.user
          // console.log(user)
          if (user.mobile && user.realname && user.bankcards.length > 0) {
            this.$router.push('/my')
          } else {
            this.$router.push('/my/bind')
          }
        } else {
          this.$toast.fail(res.data.msg)
        }
      })
    },
  },
}
</script>
